package de.schlinke_marius.acra;

import org.acra.ACRA;
import org.acra.CrashReportData;
import org.acra.ReportField;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderException;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import de.schlinke_marius.R;
import de.schlinke_marius.application.Constants;


public class CustomEmailIntentSender implements ReportSender, Constants {
	private static final String[] DEVELOPER_EMAIL_ADDRESS = new String[] { EMAIL_ADRESS_CRASHREPORT, EMAIL_ADRESS_CRASHREPORT_VIKTOR };
	private static final String E_MAIL_SUBJECT = "MS Computer Crash Report";
	private final Context mContext;

	public CustomEmailIntentSender(Context ctx) {
		mContext = ctx;
	}

	@Override
	public void send(CrashReportData errorContent) throws ReportSenderException {
		final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
		emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		emailIntent.setType("message/rfc822");
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, E_MAIL_SUBJECT);
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, buildBody(errorContent));
		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, DEVELOPER_EMAIL_ADDRESS);

		try {
			mContext.startActivity(emailIntent);
		} catch (ActivityNotFoundException anfe) {
			Toast.makeText(mContext, R.string.error_no_email_client, Toast.LENGTH_SHORT).show();
		}
	}

	private String buildBody(CrashReportData errorContent) {
		ReportField[] fields = ACRA.getConfig().customReportContent();
		if (fields.length == 0) {
			fields = ACRA.DEFAULT_MAIL_REPORT_FIELDS;
		}

		final StringBuilder builder = new StringBuilder();
		for (ReportField field : fields) {
			builder.append(field.toString()).append("=");
			builder.append(errorContent.get(field));
			builder.append("\n\n");
		}
		return builder.toString();
	}
}